package com.ren.mianshi.http;


import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * 网络请求处理，项目的网络请求处理需继承此类
 * Author: ren
 * Time: 2019/5/27
 */

public abstract class RHttpCallback<T> implements Callback<T>, IRResponse<T> {


    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if (response.code() == HttpCode.RESULT_HTTP_OK) {
            T t = response.body();
            if (t == null) {
                onFail(call, HttpCode.RESULT_ERROR, HttpMessage.DESC_DATA_ERROR);
            } else {
                onProcess(call, response);
            }
        } else {
            onFail(call, response.code(), response.code() + "");
        }
        onComplete();
    }


    @Override
    public void onFailure(Call<T> call, Throwable t) {
        if (t instanceof ConnectException || t instanceof UnknownHostException) {
            /**
             * 无网络
             */
//            if (!RNetUtil.isNetworkConnection(RApplication.getApplicaton())) {
                onFail(call, HttpCode.RESULT_NO_NET, HttpMessage.DESC_NET_DISCONNECT_ERROR);
//            } else {
//                onFail(call, HttpCode.RESULT_ERROR, HttpMessage.DESC_OTHER_ERROR);
//            }
        }
        /**
         * 连接超时
         */
        else if (t instanceof SocketTimeoutException) {
            onFail(call, HttpCode.RESULT_TIME_OUT, HttpMessage.DESC_TIME_OUT_ERROR);
        } else if (t instanceof IOException) {
            String message = t.getMessage();
            /**
             * 请求取消
             */
            if (message != null && message.equals(HttpMessage.EXCEPTION_CANCELED)) {
            } else {
                onFail(call, HttpCode.RESULT_ERROR, HttpMessage.DESC_OTHER_ERROR);
                t.printStackTrace();
            }
        } else {
            onFail(call, HttpCode.RESULT_ERROR, HttpMessage.DESC_OTHER_ERROR);
            t.printStackTrace();
        }
        onComplete();
    }

}
